
package main

import (
	"bufio"
	"fmt"
	"os"
)

func countLines(f *os.File, counts map[string]([]string), fileName string) {
	input := bufio.NewScanner(f)
	for input.Scan() {
		strs := counts[input.Text()]
		if (strs != nil) {
			app := make([]string, 1, 1)
			strs = append(strs, app...)
			strs[len(strs)-1] = fileName
			counts[input.Text()] = strs
		} else {
			counts[input.Text()] = make([]string, 1, 1)
			counts[input.Text()][0] = fileName;
		}
		
	}
}

// 修改dup2，使其可以分别打印重复的行出现在哪些文件。
func main() {
	// app := make([]string, 0, 5)
	// fmt.Println(len(app), cap(app), app)
	// app[3] = "";
	// return;
	counts := make(map[string]([]string))
	files := os.Args[1:]
	if len(files) ==0 {
		// countLines(os.Stdin, counts)
		fmt.Println("请选择文件！")
	} else {
		for _, arg := range files {
			f, err := os.Open(arg)
			if err != nil {
				fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
				continue
			}
			countLines(f, counts, arg)
			f.Close()
		}
	}
	for line, n := range counts {
		if len(n) > 1 {
			for _, fileName := range n {
				fmt.Printf("%d\t%s\t%s\n", len(n), line, fileName)
			}
		}
	}
}

